package com.czx.mpermission;

import android.Manifest;
import android.content.ContentProviderOperation;
import android.content.ContentResolver;
import android.content.OperationApplicationException;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.RemoteException;
import android.provider.ContactsContract;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

import java.util.ArrayList;

public class MainActivity extends AppCompatActivity {

    private static final String TAG = MainActivity.class.getSimpleName();
    private static final int REQUEST_CODE_ASK_PERMISSION_CONTACT = 100;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Button button = (Button) findViewById(R.id.button);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                insertDummyContactWrapper();
            }
        });
    }

    private void insertDummyContactWrapper() {
        //android M need to check permission
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            int hasWriteContactsPermission = ContextCompat.checkSelfPermission(MainActivity.this,
                    Manifest.permission.WRITE_CONTACTS);
            if(hasWriteContactsPermission != PackageManager.PERMISSION_GRANTED){
//                if(!shouldShowRequestPermissionRationale(Manifest.permission.WRITE_CONTACTS)){
//                    showMessage("You need to allow access to contacts",new DialogInterface.OnClickListener(){
//                        @Override
//                        public void onClick(DialogInterface dialogInterface, int i) {
//                            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
//                                requestPermissions(new String[]{Manifest.permission.WRITE_CONTACTS},
//                                        REQUEST_CODE_ASK_PERMISSION_CONTACT);
//                            }
//                        }
//                    });
//                    return;
//                }
                requestPermissions(new String[]{Manifest.permission.WRITE_CONTACTS},
                        REQUEST_CODE_ASK_PERMISSION_CONTACT);
            }else{
                //already asked permission
                insertDummyContact();
            }
        }else{
            //less than android M,just ask permission in Manifest
            insertDummyContact();
        }
    }

    private void insertDummyContact() {
        //two operations are needed to insert a new contact.
        ArrayList<ContentProviderOperation> operations = new ArrayList<>(2);

        //First,set up a new raw contact
        ContentProviderOperation.Builder op =
                ContentProviderOperation.newInsert(ContactsContract.RawContacts.CONTENT_URI)
                .withValue(ContactsContract.RawContacts.ACCOUNT_TYPE,null)
                .withValue(ContactsContract.RawContacts.ACCOUNT_NAME,null);
        operations.add(op.build());

        //Next,set the name for the contact.
        op = ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
                .withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, 0)
                .withValue(ContactsContract.Data.MIMETYPE,
                        ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE)
                .withValue(ContactsContract.CommonDataKinds.StructuredName.DISPLAY_NAME,
                        "__DUMMY CONTACT from runtime permissions sample");
        operations.add(op.build());

        // Apply the operations.
        ContentResolver resolver = getContentResolver();
        try {
            resolver.applyBatch(ContactsContract.AUTHORITY, operations);
        } catch (RemoteException | OperationApplicationException e) {
            Log.d(TAG, "Could not add a new contact: " + e.getMessage());
        }

    }

    @Override
    public void onRequestPermissionsResult(int requestCode,String[] permissions, int[] grantResults) {
        switch(requestCode){
            case REQUEST_CODE_ASK_PERMISSION_CONTACT:
                Log.i(TAG,"grantR:"+grantResults[0]);
                if(grantResults[0] == PackageManager.PERMISSION_GRANTED){
                    insertDummyContact();
                }else{
                    Log.i(TAG,"else");
                    Toast.makeText(MainActivity.this,"WRITE_CONTACTS Denied",Toast.LENGTH_SHORT).show();
                }
                break;
            default:
                super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        }
    }

//    private void showMessage(String message,DialogInterface.OnClickListener okListener){
//        new AlertDialog.Builder(MainActivity.this)
//                .setMessage(message)
//                .setPositiveButton("ok",okListener)
//                .setNegativeButton("cancel",null)
//                .create()
//                .show();
//    }
}
